﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UnitySceneCamera1 : MonoBehaviour
{
    public static UnitySceneCamera1 instance;
    public LayerMask layer = -1;//层  -1表示所有层
    private GameObject currentGo;//当前选中的碰撞器组件

    private void Awake()
    {
        instance = this;
    }

    private Vector3 centerPos;//围绕的中心点
    private Transform tf;//自己的transform
    public float distance2centerPos = 3f;//到中心点的距离
    private Vector3 targetPos;//摄像机要去的目标点

    //设置中心点的方法
    public void SetCenterPos(Vector3 centerPos)
    {
        this.centerPos = centerPos;
        targetPos = centerPos - tf.forward * distance2centerPos;//算出目标点
    }

    private void Start()
    {
        tf = transform;
        targetPos = transform.position;
    }
    private void Select()
    {
        if (!Input.GetMouseButtonDown(0))//点击鼠标左键发射射线
        {
            return;
        }
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        //调试画(非必要)
        Debug.DrawRay(ray.origin, ray.direction * 1000, Color.red, 10);//10是要画的长度

        RaycastHit hitInfo;
        if (Physics.Raycast(ray, out hitInfo, 1000, layer))
        {
            if (currentGo) currentGo.transform.ChangeColor(Color.white);//当前选中的变白
            hitInfo.collider.ChangeColor(Color.red);//本次点击的变红
            currentGo = hitInfo.transform.gameObject;//本次点击的成为当前选中
        }
    }
    // Update is called once per frame
    private void Update()
    {
        Select();
        //如果用户按下Alt+左键
        if (Input.GetKey(KeyCode.LeftAlt) && Input.GetKey(KeyCode.Mouse0))
        {
            //获取鼠标的滑动量
            float mosueX = Input.GetAxis("Mouse X");
            float mosueY = Input.GetAxis("Mouse Y");
            //水平围绕旋转
            tf.RotateAround(centerPos, Vector3.up, 120f * Time.deltaTime * mosueX);
            //垂直围绕旋转
            tf.RotateAround(centerPos, tf.right, -120f * Time.deltaTime * mosueY);
            targetPos = tf.position;
        }
        /*滚轮前进后退*/
        float mouseScroll = Input.GetAxis("Mouse ScrollWheel");
        targetPos +=
            transform.TransformDirection((Vector3.forward * 500 * Time.deltaTime * mouseScroll));

        //插值到目标点
        if ((targetPos - transform.position).sqrMagnitude > 0.001f)
        {
            transform.position = Vector3.Lerp(transform.position, targetPos, Time.deltaTime * 8);
        }

        if (Input.GetKeyDown(KeyCode.F))
        {
            SetCenterPos(currentGo.transform.position);
        }
    }
}